package com.laker.admin.module.excel.application.impl;

import com.laker.admin.module.excel.application.ExcelTemplateApplication;
import com.laker.admin.module.excel.domain.ExcelTemplate;
import com.laker.admin.module.excel.repository.ExcelTemplateRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.Predicate;
import java.util.Optional;


/**
 * @author : nihongxin
 * @date : 2021/3/22
 */
@Component
public class ExcelTemplateApplicationImpl implements ExcelTemplateApplication {

    @Autowired
    private ExcelTemplateRepository excelTemplateRepository;


    @Override
    public ExcelTemplate save(ExcelTemplate excelTemplate) {
        return excelTemplateRepository.save(excelTemplate);
    }


    @Override
    public void deleteById(Long id) {
        excelTemplateRepository.deleteById(id);
    }

    @Override
    public boolean checkExcelTemplateName(ExcelTemplate excelTemplate) {
        Optional<ExcelTemplate> optional = null;
        if (null == excelTemplate.getId()) {
            Specification<ExcelTemplate> specification = (root, query, criteriaBuilder) -> criteriaBuilder.and(
                    criteriaBuilder.equal(root.get("excelTemplateName"), excelTemplate.getExcelTemplateName())
            );
            optional = excelTemplateRepository.findOne(specification);

        } else {
            Specification<ExcelTemplate> specification = (root, query, criteriaBuilder) -> criteriaBuilder.and(
                    criteriaBuilder.equal(root.get("excelTemplateName"), excelTemplate.getExcelTemplateName()),
                    criteriaBuilder.notEqual(root.get("id"), excelTemplate.getId())
            );
            optional = excelTemplateRepository.findOne(specification);
        }
        return optional.isPresent() ? false : true;
    }

    @Override
    public Page<ExcelTemplate> listExcelTemplatePage(Long deptId, String keyword, Integer pageNo, Integer pageSize) {
        PageRequest page = PageRequest.of(pageNo - 1, pageSize);
        return excelTemplateRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
            Predicate conjunction = criteriaBuilder.conjunction();
            if (!StringUtils.isEmpty(keyword)) {
                conjunction.getExpressions().add(criteriaBuilder.like(root.get("excelTemplateName"), "%" + keyword + "%"));
            }
            if (null != deptId) {
                conjunction.getExpressions().add(criteriaBuilder.equal(root.get("deptId"), deptId));
            }
            return conjunction;
        }, page);
    }

    @Override
    public ExcelTemplate getById(Long id) {
        return excelTemplateRepository.getOne(id);
    }
}
